package com.spit.fammo

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.ExpandableListView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.GravityCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LogUtils
import com.spit.amoeba.base.BaseActivity
import com.spit.fammo.adapter.MainDrawerExpandableAdapter
import com.spit.fammo.api.UIHelper
import com.spit.fammo.bean.AppRoomDataBase
import com.spit.fammo.bean.DataBean
import com.spit.fammo.databinding.AMainBinding
import com.spit.fammo.ext.DOWNLOAD_PAGE
import com.spit.fammo.ext.LOG_OUT_PAGE
import com.spit.fammo.ext.POWER_SETTING_PAGE
import com.spit.fammo.ext.STOCK_TAKE_LIST_PAGE
import com.spit.fammo.ext.UPLOAD_PAGE
import com.spit.fammo.mar.MyApplication
import com.spit.fammo.mar.eventViewModel
import com.spit.fammo.util.CacheUtil
import com.spit.fammo.util.MusicUtils1
import com.spit.fammo.viewmodel.RfidModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : BaseActivity<RfidModel, AMainBinding>(),
    ExpandableListView.OnGroupClickListener,
    ExpandableListView.OnChildClickListener {

    val rfidModel: RfidModel by viewModels()

    val adapter: MainDrawerExpandableAdapter by lazy { MainDrawerExpandableAdapter(this, listDrawBean) }

    lateinit var appBarConfiguration: AppBarConfiguration

    val listDrawBean: ArrayList<DataBean> by lazy { ArrayList() }

    override fun initView(savedInstanceState: Bundle?) {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, getColor(R.color.w_f4f9fd))

        MusicUtils1.init(this)

        val tvTitle = mDatabind.navHeaderMain.findViewById<AppCompatTextView>(R.id.tv_title)
        val user = CacheUtil.getUser()
        tvTitle.text = "：" + user?.LoginID

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setSupportActionBar(mDatabind.appBarMain.includeToolbar.toolbar)
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.stockTakeListFrg,
                R.id.downloadFrg,
                R.id.uploadFrg,
                R.id.powerSettingFrg,
            ), mDatabind.drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        mDatabind.navView.setupWithNavController(navController)

        mDatabind.expandableListView.setOnGroupClickListener(this)
        mDatabind.expandableListView.setOnChildClickListener(this)
        mDatabind.expandableListView.setOnGroupExpandListener { groupPosition ->
            for (i in 0 until adapter.groupCount) {
                if (i != groupPosition) {
                    mDatabind.expandableListView.collapseGroup(i)
                }
            }
        }
        mViewModel.onMainDrawerRequest()

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                mViewModel.isOpen.value = false
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                if (!AppUtils.isAppForeground()) {
                    //app 进入后台
//                    mViewModel.isActive.set(false) //记录当前已经进入后台
                    mViewModel.isOpen.value = false
                }
            }

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)

            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
            }

        })
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

    override fun createObserver() {
        super.createObserver()
        // rfid数据接收回调
        mViewModel.rfidData.observe(this, {
//            if (!mViewModel.isScan.get())return@observe
//            LogUtils.e(it.TagId, it.Rssi)
            rfidModel.epcData.value = it
        })

        mViewModel.rfidListData.observe(this, {
            rfidModel.epcListData.value = it
        })

        //是否启动rdif
        mViewModel.isOpen.observe(this@MainActivity, { resultState ->
            if (!MyApplication.rfidError)return@observe
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                //啓動扫描才接串口
                /*if (resultState && mViewModel.initConn.get()) {
                    mViewModel.isScan.set(true)
                    mViewModel.onStart(mViewModel.tagFindParam)
                }else{
                    if (mViewModel.isScan.get()) {
                        mViewModel.isScan.set(false)
                        mViewModel.onClose()
                    }
                }*/
                //打開APP就接入串口, 当前已接入串口
                if (resultState) {
                    if (mViewModel.tagFindParam == null){//判断是否搜索
                        mViewModel.startJob()
                    }
                    mViewModel.config()
                    mViewModel.isScan.set(true)
                    mViewModel.onStart(mViewModel.tagFindParam)
                } else {
                    if (mViewModel.isScan.get()) {
                        mViewModel.cancelJob()
                        mViewModel.isScan.set(false)
                        mViewModel.onClose()
                    }
                }
            }
        })

        //指定搜索RFID
        mViewModel.isSearchOpen.observe(this, {
            if (com.blankj.utilcode.util.StringUtils.isEmpty(it)) {
                mViewModel.tagFindParam = null
                mViewModel.isOpen.value = false
            } else {
                mViewModel.tagFindParam = it
                mViewModel.isOpen.value = true
            }
        })

        mViewModel.mainDrawerListBean.observe(this, {
            listDrawBean.addAll(it)
            mDatabind.expandableListView.setAdapter(adapter)
            adapter.notifyDataSetChanged()
            mViewModel.mainDrawerUploadNum.value = 0
        })

        mViewModel.mainDrawerUploadNum.observe(this, {
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                val uploadOrderListDao = AppRoomDataBase.get().getUploadOrderListDao()
                val all = uploadOrderListDao.findAll().size
                withContext(Dispatchers.Main) {
                    var bean = listDrawBean.find { it.Type == UPLOAD_PAGE }
                    bean?.num = all
                    adapter.notifyDataSetChanged()

                    val tvNum = mDatabind.appBarMain.includeToolbar.tvNum
                    if (all > 0) {
                        tvNum.visibility = View.VISIBLE
                        if (all < 100) {
                            tvNum.text = all.toString()
                        } else {
                            tvNum.text = "99+"
                        }
                    } else {
                        tvNum.visibility = View.GONE
                    }
                }
            }
        })

        eventViewModel.playMusic.observeInActivity(this, Observer {
            if (it){
                MusicUtils1.play()
            }else{
                MusicUtils1.stop()
            }
        })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            mViewModel.KEYCODE_MEDIA_NEXT.get() -> {
                /*if (event?.repeatCount == 0) {
                    mViewModel.longPressNext.set(false)
                    event.startTracking()
                    return true
                }*/
            }
            4 ->{
                onBackPressed()
            }
        }
        return false
    }

    override fun onKeyLongPress(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            mViewModel.KEYCODE_MEDIA_NEXT.get() -> {
                mViewModel.longPressNext.set(true)
                eventViewModel.longPressKeyCode.value = 1
                return true
            }
        }
        return super.onKeyLongPress(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            mViewModel.KEYCODE_MEDIA_NEXT.get() -> {
                if (!mViewModel.longPressNext.get()) {
                    eventViewModel.longPressKeyCode.value = 0
                } else {
                    eventViewModel.longPressKeyCode.value = 2
                    mViewModel.longPressNext.set(false)
                }
            }
        }
        return super.onKeyUp(keyCode, event)
    }

    //region mainDraw 跳转事件
    override fun onGroupClick(p0: ExpandableListView?, p1: View?, p2: Int, p3: Long): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        val bean = listDrawBean.get(p2)
        when(bean.Type){
            STOCK_TAKE_LIST_PAGE -> UIHelper.startStockTakeListFrg(navController)
            DOWNLOAD_PAGE -> UIHelper.startDownloadFrg(navController)
            UPLOAD_PAGE -> UIHelper.startUploadFrg(navController)
            POWER_SETTING_PAGE -> UIHelper.startPowerSettingFrg(navController)
            LOG_OUT_PAGE -> {
                val user = CacheUtil.getUser()
                user?.Password = null
                CacheUtil.setUser(user)
                UIHelper.startLoginAct()
                ActivityUtils.finishAllActivities()
            }
        }
        mDatabind.drawerLayout.closeDrawers()
        return true
    }

    override fun onChildClick(
        p0: ExpandableListView?,
        p1: View?,
        p2: Int,
        p3: Int,
        p4: Long
    ): Boolean {
        TODO("Not yet implemented")
    }
    //endregion

    var exitTime = 0L
    override fun onBackPressed() {
        if (mDatabind.drawerLayout.isDrawerOpen(GravityCompat.END)) {
            mDatabind.drawerLayout.closeDrawers()
        } else {
            val nav = Navigation.findNavController(this@MainActivity, R.id.nav_host_fragment_content_main)
            val currentDestinationId = nav.currentDestination?.id
            if (currentDestinationId != null && !appBarConfiguration.topLevelDestinations.contains(currentDestinationId)) {
                nav.navigateUp()
            } else {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                    exitTime = System.currentTimeMillis()
                } else {
                    finish()
                }
            }
        }
    }
}